﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Objects;
using System.Data.Entity;//如果不加载则不能使用IDbSet<Query>.include

namespace Htinns.GatewayConsole.Models
{
	public class ModuleService
	{
		public static IEnumerable<ModuleAssign> GetModules(string hotelId)
		{
			using(GatewayContext db=new GatewayContext())
			{
				var modules=db.ModuleAssigns.Where(m=>m.HotelId==hotelId).ToList();

				return modules;
			}
		}

		public static Vote GetPublicVote(string hotelId) 
		{
			Vote vote;

			using (GatewayContext db = new GatewayContext())
			{
				
				var module = db.ModuleAssigns.Where(m => m.HotelId ==ConstTypes.Questionnaire_PublicId  && m.Position == ConstTypes.ModulePosition_Public).FirstOrDefault();

				//EF多重加载
				vote = db.Votes.Include(i=>i.VoteItems.Select(s=>s.VoteSheets)).SingleOrDefault(v => v.Id == module.ModuleId);//.find		

				double voteSheetCount = db.VoteSheets.Count(v => v.HotelId == hotelId && v.Vote.Id==vote.Id);

				LoadVoteItemsPrecent(vote,hotelId,voteSheetCount);		
			}

			return vote;
		}

		public static void LoadVoteItemsPrecent(Vote vote,string hotelId,double voteSheetCount)
		{
			if(voteSheetCount<1) return;

			foreach (var item in vote.VoteItems) 
			{				
				double itemCount=(double)item.VoteSheets.Where(i=>i.HotelId==hotelId).Count();			

				item.Percent = Math.Round(itemCount / voteSheetCount * 100.00, 2);
			}
			//return vote;
		}


		public static int GetVoteSheetCount(Vote vote,string hotelId)
		{
			using (GatewayContext db = new GatewayContext())
			{
				return db.VoteSheets.Count(v => v.HotelId == hotelId && v.Vote.Id == vote.Id);
				
			}
		}

		public static IEnumerable<VoteSheet> GetSheetMsg(Vote vote, string hotelId,DateTime beginDate,DateTime endDate) 
		{
			IList<VoteSheet> sheets = new List<VoteSheet>();

			using (GatewayContext db = new GatewayContext())
			{
				sheets=db.VoteSheets.Where(s => s.Vote.Id == vote.Id && s.HotelId == hotelId
					&& s.CreatedDate >= beginDate && s.CreatedDate <= endDate &&!string.IsNullOrEmpty(s.Description) ).ToList();

				
			}

			return sheets;
		}
	}

}